package JPetStore.web.servlet;

import JPetStore.domain.Account;
import JPetStore.domain.Cart;
import JPetStore.domain.CartItem;
import JPetStore.persistence.CartDao;
import JPetStore.persistence.impl.CartDaoImpl;
import JPetStore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Iterator;

public class UpdateCartServlet extends HttpServlet {

    private static final String CART_FORM = "/WEB-INF/jsp/cart/cart.jsp";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        Cart cart = (Cart) session.getAttribute("cart");
        if(cart == null)
        {
            req.getRequestDispatcher(CART_FORM).forward(req, resp);
            return;
        }
        Account loginAccount = (Account) session.getAttribute("loginAccount");
        Iterator<CartItem> cartItems = cart.getAllCartItems();
        while (cartItems.hasNext()) {
            CartItem cartItem = (CartItem) cartItems.next();
            String itemId = cartItem.getItem().getItemId();
            try {
                // 怎么拿到这个Id呢, 匹配后端的那个Id ???
                // 这个是把修改后的拿到后, 把所有的都重新设置
                // 比如 2 3 2, 前端的Quantity栏改成 2 1 2
                // 实际上是把2 1 2拿到后给他重新进行设置
                String quantityString = req.getParameter(itemId);
                int quantity = Integer.parseInt(quantityString);
                cart.setQuantityByItemId(itemId, quantity);
                if (quantity < 1) {
                    cartItems.remove();
                }
            } catch (Exception e) {
                //ignore parse exceptions on purpose
            }
        }
        try{
            CartDao cartDao = new CartDaoImpl();
            cartDao.deleteAll(loginAccount);
            cartDao.insertCart(cart.getCartItemList(),loginAccount);
        }catch (Exception e){
            e.printStackTrace();
        }
        if (loginAccount != null) {
            String username = loginAccount.getUsername();
            String strBackUrl = "http://" + req.getServerName() + ":" + req.getServerPort()
                    + req.getContextPath() + req.getServletPath() + "?" + (req.getQueryString());
            LogService logService = new LogService();
            String logInfo = logService.logInfo(new Object[]{" "}) + strBackUrl + "更新了购物车";
            logService.insertLogInfo(username, logInfo);
        }
//        req.getRequestDispatcher(CART_FORM).forward(req, resp);

    }
}
